package lx.scrmXj;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Record;
import lx.util.DateUtil;
import lx.util.HttpHelper;
import lx.util.StrUtil;

import java.text.MessageFormat;
import java.util.*;

/**
 * @Description: 成员消息发送
 * @Author: 李星 lixing_java@163.com
 * @Date: 2020/3/14 12:52
 */
public class MessageStaffTask extends TimerTask {
    // 发送应用消息
    String message_staff_url = "https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token={0}";

    @Override
    public void run() {
        List<Record> recordList = Db.find("SELECT * FROM XJ_SCRM_MESSAGE_STAFF WHERE BOOLEANSTATE = '0' AND STATE = 0 AND MSGTIME <= SYSDATE");  // 查询所有未发送的成员信息
        try {
            System.out.println(MessageFormat.format("{0} 当前员工信息列表：{1}",DateUtil.dateToDateTimeCharacter(new Date()),recordList.size()));
            for (Record record : recordList) {
                messageStaff(record); // 发送员工信息
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void messageStaff(Record record) {
        try {
            String msgtype = record.getStr("MSGTYPE"); // 消息类型
            String id = record.getStr("ID"); // 消息关联id
            String msgmsgid = "";//消息返回的msgid, 用作获取群发消息结果（员工消息的发送中暂时用不到）
            //
            String arrpeople = record.getStr("ARRPEOPLE"); // 成员的userid，多个以逗号分隔，格式：1，2，3
            StringBuilder stringBuilderToUser = new StringBuilder();
            if ("@all".equals(arrpeople)) {
                stringBuilderToUser.append("@all");
            } else {
                List<String> useridlist = Arrays.asList(arrpeople.split(","));
                int size = useridlist.size();
                for (int i = 0; i < size; i++) {
                    if (i < size - 1) {
                        stringBuilderToUser.append(useridlist.get(i)).append("|");
                    } else {
                        stringBuilderToUser.append(useridlist.get(i));
                    }
                }
            }

            // TODO 员工消息入参
            JSONObject staffJson = new JSONObject();

            // todo touser 指定接收消息的成员，成员ID列表（多个接收者用‘|’分隔，最多支持1000个），@all则向该企业应用的全部成员发送
            staffJson.put("touser", stringBuilderToUser.toString());
            if ("@all".equals(arrpeople)) {
                //
            } else {
                // todo 指定接收消息的部门，部门ID列表，多个接收者用‘|’分隔，最多支持100个。 当touser为”@all”时忽略本参数
                // staffJson.put("toparty", stringBuilderToUser.toString());
                // todo 指定接收消息的标签，标签ID列表，多个接收者用‘|’分隔，最多支持100个。当touser为”@all”时忽略本参数
                // staffJson.put("totag", stringBuilderToUser.toString());
            }
            staffJson.put("agentid", "1000008"); // 企业应用id
            if (msgtype.equals("1")) {  // TODO --------------------------------------------------------------------文本
                staffJson.put("msgtype", "text");
                JSONObject text = new JSONObject();
                text.put("content", record.getStr("marktext"));
                staffJson.put("text", text);
            } else if (msgtype.equals("2")) {  // TODO -------------------------------------------------------------图片
                staffJson.put("msgtype", "image");
                JSONObject image = new JSONObject();
                image.put("media_id", record.getStr("sucaiid"));
                staffJson.put("image", image);
            } else if (msgtype.equals("3")) {  // TODO -------------------------------------------------------------图文
                staffJson.put("msgtype", "news");
                JSONObject news = new JSONObject();
                JSONArray articles = new JSONArray();
                JSONObject artjson = new JSONObject();
                artjson.put("title", record.getStr("marktext"));
                artjson.put("description", record.getStr("msgtext"));
                artjson.put("url", record.getStr("imgtexturl"));
                artjson.put("picurl", record.getStr("imgurl"));
                articles.add(artjson);
                news.put("articles", articles);
                staffJson.put("news", news);
            } else if (msgtype.equals("4")) { // TODO ----------------------------------------------------------- 小程序
//                "miniprogram_notice" : {
//                    "appid": "wxbbd2f2eca0b9e42e",
//                    "page": "pages/index/index",
//                    "title": "会议室预订成功通知",
//                    "description": "4月27日 16:16",
//                    "emphasis_first_item": true,
//                    "content_item": [
//                            {
//                                "key": "会议室",
//                                    "value": "402"
//                            },
//                            {
//                                "key": "会议地点",
//                                    "value": "广州TIT-402会议室"
//                            },
//                            {
//                                "key": "会议时间",
//                                    "value": "2018年8月1日 09:00-09:30"
//                            },
//                            {
//                                "key": "参与人员",
//                                    "value": "周剑轩"
//                            }
//                    ]
//                },
                staffJson.remove("agentid");
                staffJson.put("msgtype", "miniprogram_notice");

                JSONObject miniprogram_notice = new JSONObject();
                miniprogram_notice.put("appid", record.getStr("smallappid")); // wxbbd2f2eca0b9e42e 小程序appid，必须是与当前小程序应用关联的小程序
                miniprogram_notice.put("page", record.getStr("smallpageurl")); // /pages/index/index 点击消息卡片后的小程序页面，仅限本小程序内的页面。该字段不填则消息点击后不跳转
                miniprogram_notice.put("title", record.getStr("smalltitle")); // 消息标题，长度限制4-12个汉字（支持id转译）
                //
//                miniprogram_notice.put("description", record.getStr("description")); // 消息描述，长度限制4-12个汉字（支持id转译）
//                miniprogram_notice.put("emphasis_first_item", true); // 是否放大第一个content_item
//                JSONObject item1 = new JSONObject();
//                item1.put("key", "会议室");
//                item1.put("value", "402");
//                JSONArray content_item = new JSONArray(); // 消息内容键值对，最多允许10个item
//                content_item.add(0,item1);
//                miniprogram_notice.put("content_item", content_item);
                //
                staffJson.put("miniprogram_notice", miniprogram_notice);
            } else if (msgtype.equals("5")) { // TODO --------------------------------------------------------  markdown
                staffJson.put("msgtype", "markdown");
                JSONObject markdown = new JSONObject();
                markdown.put("content", record.getStr("markdowntext"));
                staffJson.put("markdown", markdown);
            } else if (msgtype.equals("6")) { // TODO -------------------------------------------------------- 音频
                staffJson.put("msgtype", "voice");
                JSONObject voice = new JSONObject();
                voice.put("media_id", record.getStr("sucaiid"));
                staffJson.put("voice", voice);
            } else if (msgtype.equals("7")) { // TODO -------------------------------------------------------- 视频
                staffJson.put("msgtype", "video");
                JSONObject video = new JSONObject();
                video.put("media_id", record.getStr("sucaiid"));
                video.put("title", record.getStr("marktext"));
                video.put("description", record.getStr("msgtext"));
                staffJson.put("video", video);
            } else if (msgtype.equals("8")) { // TODO -------------------------------------------------------- 文件
                staffJson.put("msgtype", "file");
                JSONObject file = new JSONObject();
                file.put("media_id", record.getStr("sucaiid"));
                staffJson.put("file", file);
            } else if (msgtype.equals("9")) {   // TODO -------------------------------------------------------- 文本卡片
                staffJson.put("msgtype", "textcard");
                JSONObject textcard = new JSONObject();
                textcard.put("title", "消息通知");// 标题
                textcard.put("description", record.getStr("marktext"));     // 内容
                textcard.put("url", record.getStr("reurl")); // 跳转连接
                staffJson.put("textcard", textcard);
            } else if (msgtype.equals("10")) {  // TODO -------------------------------------------------------- 任务卡片
                staffJson.put("msgtype", "taskcard");
                //
                JSONObject taskcard = new JSONObject();
                taskcard.put("title", "消息通知");
                taskcard.put("description", record.getStr("marktext"));
                if (!StrUtil.isEffective(record.getStr("reurl"))) {
                    taskcard.put("url", record.getStr("reurl"));
                }
                taskcard.put("task_id", UUID.randomUUID());
                //
                JSONObject btn1 = new JSONObject();
                btn1.put("key", "key01");
                btn1.put("name", record.getStr("buttonname1"));

                JSONObject btn2 = new JSONObject();
                btn2.put("key", "key02");
                btn2.put("name", record.getStr("buttonname2"));

                JSONArray btnarr = new JSONArray();
                btnarr.add(btn1);
                btnarr.add(btn2);
                //
                taskcard.put("btn", btnarr);

                staffJson.put("taskcard", taskcard);
            }

            int state = 0; // 发送状态( 0:未发送 1:已发送 2:发送失败)
            String msgstate = "";// 发送结果
            String res;

            // 获取token，发送消息的必要条件
            int category = 3;
            if ("4".equals(msgtype)) {
                category = 4;
            }
            String tokenUrl = "SELECT ACCESS_TOKEN FROM XJ_SCRM_TOKEN where CATEGORY = "+category+" ORDER BY CREATE_TIME DESC";
            List<Record> recordTokenList = Db.find(tokenUrl);
            if (recordTokenList.size() > 0) {
                String token = recordTokenList.get(0).getStr("ACCESS_TOKEN");
                System.out.println(MessageFormat.format("{0} TOKEN：{1}", DateUtil.dateToDateTimeCharacter(new Date()), token));
                // 发送客户消息
                System.out.println(MessageFormat.format("{0} 发送成成员消息入参报文：{1}", DateUtil.dateToDateTimeCharacter(new Date()),staffJson));
                res = HttpHelper.sendRequestHttps(MessageFormat.format(message_staff_url, token), "POST", staffJson);
                System.out.println(MessageFormat.format("{0} 发送成成员消息出参报文：{1}", DateUtil.dateToDateTimeCharacter(new Date()),res));
                JSONObject respjson = JSONObject.parseObject(res);
                if ("0".equals(respjson.getString("errcode"))) { // "errcode":0,"errmsg":"ok. Warning: wrong json format.
                    msgstate = "发送成功";
                    state = 1;
                } else {
                    msgstate = "发送失败";
                    state = 2;
                }
                System.out.println("成员消息发送结束，发送结果：" + msgstate + "," + state);
            } else {
                msgstate = "发送失败";
                state = 2;
                res = "从本地服务器获取TOKEN失败";
            }
            //
            int updateState = Db.update("UPDATE XJ_SCRM_MESSAGE_STAFF SET STATE=? WHERE ID=?", state, id);
            System.out.println("更新员工消息的发送状态结果：" + updateState);
            //
            Record insertRecord = new Record();
            insertRecord.set("ID",UUID.randomUUID().toString());
            insertRecord.set("MSGTYPE",msgtype);
            insertRecord.set("MSGID",id);
            insertRecord.set("REQ",staffJson.toString());
            insertRecord.set("RESP",res);
            insertRecord.set("MSGSTATE",msgstate);
            insertRecord.set("MSGMSGID",msgmsgid);
            boolean insertState = Db.save("XJ_SCRM_MESSAGE_RESP", "ID", insertRecord);
            System.out.println("添加员工消息发送记录结果：" + insertState);
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("员工消息发送出错：" + e.getMessage());
        }

    }

}
